﻿/* $RCSFile: PrivateDownLoad.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/PrivateDownLoad.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Globalization;
using System.Diagnostics;
using System.IO;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Collections.Generic;
using System.Web.Security;
using System.Xml;
using System.Configuration;

using AddonNice;
using AddonNice.Authentication;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using AddonNice.CRMEMailing;
using AddonNice.Settings.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.DownloadSession
{
 	#region Local TraceSwitch 
	
    public class PrivateDownloadTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("PrivateDownloadTrace","Special Trace Switch for PrivateDownloadTrace");
	}
	
    #endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for PrivateDownLoad 
    /// </summary>
    public class PrivateDownLoadSI : PortalCRMModuleControlSI
    {
        public PrivateDownLoadSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( PrivateDownloadTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDownLoadSI Ctor BEG.",PrivateDownloadTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( PrivateDownloadTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDownLoadSI Ctor END.",PrivateDownloadTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( PrivateDownloadTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDownLoadSI InitSettings BEG.",PrivateDownloadTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                               =   pm.ExtendedResourcesGroup;

			SettingItemSpecial RequireRegistered	    =   new SettingItemSpecial(AStr.RequireRegistered,new BooleanDataType());
			RequireRegistered.Value				        =   StStr.strFalse;
			RequireRegistered.Order				        =   10;
            RequireRegistered.Group                     =   SettingItemGroup.MODULE_SPECIAL_SETTINGS; // necessary to split tabs
            RequireRegistered.ExtendedGroupName         =   extgrp;
            RequireRegistered.ResourceFile              =   AStr.ResourceFile;
            RequireRegistered.ResourceItem              =   AStr.ResourceItem;
            RequireRegistered.EnglishName			    =   "Requires Registered users";
            RequireRegistered.Description			    =   "Allows only registered users to download";
			bSettings.AddSetting(RequireRegistered);

            SettingItemSpecial Transfer2Register	    =   new SettingItemSpecial(AStr.Transfer2Register,new BooleanDataType());
			Transfer2Register.Value				        =   StStr.strFalse;
			Transfer2Register.Order				        =   20;
            Transfer2Register.Group                     =   SettingItemGroup.MODULE_SPECIAL_SETTINGS; // necessary to split tabs
            Transfer2Register.ExtendedGroupName         =   extgrp;
            Transfer2Register.ResourceFile              =   AStr.ResourceFile;
            Transfer2Register.ResourceItem              =   AStr.ResourceItem;
            Transfer2Register.EnglishName			    =   "Auto transfer to register page";
            Transfer2Register.Description			    =   "When only registered users allowed to download, transfer directly to register page";
			bSettings.AddSetting(Transfer2Register);
            if ( PrivateDownloadTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]PrivateDownLoadSI InitSettings END.",PrivateDownloadTrace.Sw.Info);
        }
    }
    /// <summary>
    /// Page containing this module is called from a link in an email sent by bulk mail
    /// It receive in parameters:
    /// - a type of request: rq= values are from an enum;
    ///     all documents=1,Same for all=2
    ///   so 
    ///   rq=0 means 1 document dedicated by target: we should receive the DB document id in the d= parameter
    ///   rq=1 means all documents dedicated by target: we should receive the DB targetid in the t= parameter
    ///   rq=2 means 1 same document for all targets: we should receive the DB document id in the d= parameter
    ///   rq=3 means same all documents for all targets: this case is not solved 'how to retrieve this document list ?' 
    ///     
    /// </summary>
    public partial class PrivateDownLoad : PortalEmailingModule
    {
        XrmEMailingDB dwnDB               =   new XrmEMailingDB();

		#region Global Implementation

        public override Guid GuidID 
		{
			get
			{
				return new Guid(AStr.PrivateDownLoadGuid);
			}
		}

		#endregion Global Implementation
        
        #region Ctor

        public PrivateDownLoad()
        {
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad Ctor enter at: {0}", DateTime.UtcNow), PrivateDownloadTrace.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                         =   "PRIVATEDOWNLOAD";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new PrivateDownLoadSI(bSettings,this);
        }

        #endregion Ctor

        protected void Page_Load(object sender, EventArgs e)
        {
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad Page_Load BEG IsPostBack: {0}",IsPostBack),PrivateDownloadTrace.Sw.Info);
            if ( ! IsPostBack )
            {
                try
                {
                    bool userLgd                        =   UserLogged;
                    if ( userLgd )
                    {
                        AddonNiceMembershipUser user    =   (AddonNiceMembershipUser)Membership.GetUser();
                    }
                    // then free products available for everybody depending on settings
                    if ( userLgd || !Settings[AStr.RequireRegistered].ToBool() )
                    {
                    }
                    else if ( !userLgd && Settings[AStr.Transfer2Register].ToBool() )
                    {
                        string NavigateUrl                  =   HttpUrlBuilder.BuildUrl("~/register.aspx",true,DynPageLoc.Login,StStr.RegisterPageID);
                        ADNPage.Redirect(NavigateUrl,true);
                    }
                }
                catch(Exception ex)
                {
                    if (PrivateDownloadTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDownLoad Page_Load ex: {0}",ex),PrivateDownloadTrace.Sw.Info);
                    throw;
                }
            }
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad Page_Load END.",PrivateDownloadTrace.Sw.Info);
        }

        DataTable MakeTb()
        {
            DataTable Tb    =   new DataTable("PrivateDoc");
            Tb.Columns.Add("ItemID",typeof(int));
            Tb.Columns.Add("itemcrmid",typeof(Guid));
            Tb.Columns.Add("Title" ,typeof(string));
            Tb.Columns.Add("FileName",typeof(string));
            Tb.Columns.Add("CreatedDate",typeof(DateTime));
            Tb.Columns.Add("Category" ,typeof(string));
            Tb.Columns.Add("ContentSize",typeof(int));
            Tb.Columns.Add("ContentType",typeof(string));
            return Tb;
        }

        ///   rq=0 means 1 document dedicated by target: we should receive the DB document id in the d= parameter
        DataTable DisplayDoc()
        {
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad DisplayDoc BEG.",PrivateDownloadTrace.Sw.Info);
            DataTable tb                    =   MakeTb();
            string strdoc                   =   Request.QueryString["d"];
            if ( string.IsNullOrEmpty(strdoc) )
                return tb;  
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad DisplayDoc strdoc: {0}",strdoc),PrivateDownloadTrace.Sw.Info);
            int docId                       =   int.Parse(strdoc);
            SqlDataReader dr                =   null;
            try
            {
                dr                          =   dwnDB.GetPrivateDocument(docId);
                if ( dr.Read() )
                {
                    string filename         =   (string)dr[AStr.DBFilename];
 			        if (PrivateDownloadTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad DisplayDoc filename: {0}",filename),PrivateDownloadTrace.Sw.Info);
                    DataRow rw              =   tb.NewRow();
                    rw["ItemID"]            =   docId;
                    rw["itemcrmid"]         =   Guid.Empty;
                    rw["Title"]             =   (string)dr[AStr.DBFilename];
                    rw["FileName"]          =   filename;
                    rw["CreatedDate"]       =   (DateTime)dr[AStr.DBCreatedDate];
                    rw["Category"]          =   (string)dr[AStr.DBFilename];
                    rw["ContentSize"]       =   (int)dr[AStr.DBFilename];
                    int idx                 =   filename.LastIndexOf('.');
                    if (( idx > -1 ) && ( idx < filename.Length ) )
                    {
                        string ext          =   filename.Substring(idx+1);
                        rw["ContentType"]   =   DocumentsHelper.GetImage(ext);
                    }
                    tb.Rows.Add(rw);
                }
            }
            catch ( Exception ex )
            {
                if (PrivateDownloadTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDownLoad DisplayDoc ex: {0}",ex),PrivateDownloadTrace.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null )
                    dr.Close();
            }
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad DisplayDoc END.",PrivateDownloadTrace.Sw.Info);
            return tb;
        }

        ///   rq=1 means all documents dedicated by target: we should receive the DB targetid in the t= parameter
        DataTable DisplayAllDoc()
        {
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad DisplayAllDoc BEG.",PrivateDownloadTrace.Sw.Info);
             DataTable tb                    =   MakeTb();
            string strdoc                   =   Request.QueryString["d"];
            if ( string.IsNullOrEmpty(strdoc) )
                return tb;  
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad DisplayAllDoc strdoc: {0}",strdoc),PrivateDownloadTrace.Sw.Info);
            int docId                       =   int.Parse(strdoc);
            SqlDataReader dr                =   null;
            try
            {
                dr                          =   dwnDB.GetPrivateDocument(docId);
                if ( dr.Read() )
                {
                    string filename         =   (string)dr[AStr.DBFilename];
			        if (PrivateDownloadTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad DisplayAllDoc filename: {0}",filename),PrivateDownloadTrace.Sw.Info);
                    DataRow rw              =   tb.NewRow();
                    rw["ItemID"]            =   docId;
                    rw["itemcrmid"]         =   Guid.Empty;
                    rw["Title"]             =   (string)dr[AStr.DBTitle];
                    rw["FileName"]          =   filename;
                    rw["CreatedDate"]       =   (DateTime)dr[AStr.DBCreatedDate];
                    rw["Category"]          =   (string)dr[AStr.DBCategory];
                    rw["ContentSize"]       =   (int)dr[AStr.DBContenSize];
                    int idx                 =   filename.LastIndexOf('.');
                    if (( idx > -1 ) && ( idx < filename.Length ) )
                    {
                        string ext          =   filename.Substring(idx+1);
                        rw["ContentType"]   =   DocumentsHelper.GetImage(ext);
                    }
                    tb.Rows.Add(rw);
                }
            }
            catch ( Exception ex )
            {
                if (PrivateDownloadTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDownLoad DisplayAllDoc ex: {0}",ex),PrivateDownloadTrace.Sw.Info);
                throw;
            }
            finally
            {
                if ( dr != null )
                    dr.Close();
            }
			if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad DisplayAllDoc END.",PrivateDownloadTrace.Sw.Info);
            return tb;
        }

       #region Image documents
        private void SetImages(DataTable dv)
        {
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]PrivateDownLoad setDataView begin.",PrivateDownloadTrace.Sw.Info);
            foreach (DataRow dr in dv.Rows)
            {
                dr["contentType"]   =   DocumentsHelper.GetImage((string)dr["contentType"]);
            }
        }
 
       #endregion

        public string GetBrowsePath(int ItemID,Guid itemcrmid)
        {
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad GetBrowsePath BEG ItemID: {0}, itemcrmid: {1}.",ItemID,itemcrmid),PrivateDownloadTrace.Sw.Info);
            string url  =   (itemcrmid == Guid.Empty ) ? string.Format("{0}/DownloadSession/DownLoadGenerator.aspx?id={1}",Config.ModulesPath,ItemID)
                : string.Format("{0}/DownloadSession/DownLoadGenerator.aspx?id={1}&crmid={2}",Config.ModulesPath,ItemID,itemcrmid);
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad GetBrowsePath END url: {0}.",url),PrivateDownloadTrace.Sw.Info);
            return url;
        }

        void myDataGrid_NeedDataSource(object source,GridNeedDataSourceEventArgs e)
        {
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad myDataGrid_NeedDataSource BEG RebindReason: {0}.",e.RebindReason),PrivateDownloadTrace.Sw.Info);
            try
            {
                if ( Request.QueryString["rq"]  == null )
                    return;
                string rqType                           =   Request.QueryString["rq"];
                if (PrivateDownloadTrace.Sw.TraceVerbose)
                    Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad myDataGrid_NeedDataSource rqType: {0}.",rqType),PrivateDownloadTrace.Sw.Info);
                int TpReq                               =   int.Parse(rqType);
                DataTable Tb                            =   null;
                switch ( TpReq )
                {
                    ///   rq=0 means 1 document dedicated by target: we should receive the DB document id in the d= parameter
                    case 0:
                    Tb                                  =   DisplayDoc();
                    break;

                    ///   rq=1 means all documents dedicated by target: we should receive the DB targetid in the t= parameter
                    case 1:
                    Tb                                  =   DisplayAllDoc();
                    break;

                    ///   rq=2 means 1 same document for all targets: we should receive the DB document id in the d= parameter
                    case 2:
                    Tb                                  =   DisplayDoc();
                    break;

                    ///   rq=3 means same all documents for all targets: this case is not solved 'how to retrrieve this document list ?' 
                    case 3:
                    break;

                    default:
                    return;
                }
                myDataGrid.DataSource   =   Tb;
            }
            catch (Exception ex)
            {
                if (PrivateDownloadTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDownLoad myDataGrid_NeedDataSource ex: {0}", ex),PrivateDownloadTrace.Sw.Info);
                throw;
            }
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad myDataGrid_NeedDataSource END.",PrivateDownloadTrace.Sw.Info);
        }

        void myDataGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad myDataGrid_ItemDataBound BEG ItemType: {0}", e.Item.ItemType),PrivateDownloadTrace.Sw.Info);
            try
            {
               if (e.Item.ItemType != GridItemType.Item     
                    && e.Item.ItemType != GridItemType.AlternatingItem 
                    && e.Item.ItemType != GridItemType.SelectedItem )
                    return;

                Control ctl                         =   e.Item.Cells[1].FindControl("contentType");
                if (ctl is HyperLink)
                {
                    if (PrivateDownloadTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PrivateDownLoad myDataGrid_ItemDataBound  SkinId: {0}, NavigateUrl: {1}, ImageUrl: {2}",
                            ((HyperLink)ctl).SkinID,((HyperLink)ctl).NavigateUrl,((HyperLink)ctl).ImageUrl),PrivateDownloadTrace.Sw.Info);
                }
            }
            catch (Exception ex)
            {
                if (PrivateDownloadTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PrivateDownLoad myDataGrid_ItemDataBound ex: {0}", ex),PrivateDownloadTrace.Sw.Info);
                throw;
            }
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad myDataGrid_ItemDataBound END.",PrivateDownloadTrace.Sw.Info);
        }

        #region Std overrides 

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            //string strcult              =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

		override protected void OnInit(EventArgs e)
		{
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad OnInit BEG.",PrivateDownloadTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if (PrivateDownloadTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]PrivateDownLoad OnInit END.",PrivateDownloadTrace.Sw.Info);
		}
        

        private void InitializeComponent()
        {
            Load                        +=  new EventHandler(Page_Load);
            myDataGrid.NeedDataSource   +=  new GridNeedDataSourceEventHandler(myDataGrid_NeedDataSource);
            myDataGrid.ItemDataBound    +=  new GridItemEventHandler(myDataGrid_ItemDataBound);
        }
        #endregion
    }
}